/*
* @Author: wangliang
* @Date: 2018/4/11
* @description: 竞品信息
*/
<template>
    <div class="custom-box p-20 m-t-20">
        <el-row>
            <el-col :span="20" class="ca-title">
                <h3>竞品信息 ({{totalCount}})</h3>
                <button type="button" 
                    class="custom-btn custom-btn-round m-l-15"
                    @click="addDialog(-1)">
                    <i class="fa fa-plus"></i>
                </button>
                <Operate
                :operateType="'operativeCompetitors'"
                @getOperateNum="getOperateNum"
                />
            </el-col>
        </el-row>
        <el-table
            ref="multipleTable"
            stripe
            :data="competitorList"
            style="width: 100%">
            <el-table-column
                label="企业名称"
                prop="competitorCompanyName"
                align="center">
            </el-table-column>
            <el-table-column
                label="产品名称"
                prop="productName"
                align="center">
            </el-table-column>
            <el-table-column
                label="当前轮次"
                prop="competitorRound"
                align="center">
            </el-table-column>
            <el-table-column
                label="行业"
                prop="industry"
                align="center">
            </el-table-column>
            <el-table-column
                label="业务"
                prop="business"
                align="center">
            </el-table-column>
            <el-table-column
                label="成立时间"
                prop="establishTime"
                align="center">
            </el-table-column>
            <el-table-column
                label="估值"
                prop="valuation"
                align="center">
            </el-table-column>
            <el-table-column
                label="操作"
                prop=""
                align="center">
                <template slot-scope="scope">
                    <el-button  type="text" @click='editInfo(scope.row)'>编辑</el-button>
                    <el-button  type="text" @click='deleteInfo(scope.row.id)'>删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="m-t-20" >
            <el-pagination
                layout="prev, pager, next"
                :total="totalCount">
            </el-pagination>
        </div>
        <!-- 编辑竞品信息 -->
        <el-dialog title="竞品信息" :visible.sync="dialogVisible"  width="35%" :close-on-click-modal='false'>
             <el-form :model='comCompetitor' ref="competiteForm" :rules="rules">
                <el-row :gutter="5">
                    <el-col :span="12">
                        <el-form-item label="企业名称" label-width="90px" prop='competitorCompanyName'>
                            <el-input v-model="comCompetitor.competitorCompanyName" style="width: 100%;"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="" label-width="0px">
                            <el-select v-model="searchType" placeholder="请选择">
                            <el-option
                            v-for="(item, index) in openSearchNameType"
                            :key="index"
                            :label="item.dictName"
                            :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="" label-width="0px">
                            <el-button type="primary" @click="getEnterprise">搜索</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
           
                <el-row>
                    <el-col :span="16">
                        <el-form-item label="产品名称" label-width="90px" prop='competitorProductId'>
                            <el-select v-model="comCompetitor.competitorProductId" placeholder="请选择" @change='changeProduct'>
                                <el-option v-for="(item,index) in productList"
                                :key='index'
                                :label="item.product"
                                :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="地区" label-width="90px" prop='competitorArea'>
                            <el-input v-model="comCompetitor.competitorArea"  :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="当前轮次" label-width="90px" prop='competitorRound'>
                            <el-input v-model="comCompetitor.competitorRound"  :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="行业" label-width="90px" prop='industry'>
                            <!-- <el-autocomplete v-model="comCompetitor.industry"  
                              :fetch-suggestions="seachIndustry"
                              :trigger-on-focus="false">
                             </el-autocomplete> -->
                             <el-autocomplete v-model="comCompetitor.industry"  
                              :fetch-suggestions="seachIndustry">
                             </el-autocomplete>
                        </el-form-item>
                        <el-form-item label="业务" label-width="90px" prop='business'>
                            <!-- <el-autocomplete v-model="comCompetitor.business"  
                             :fetch-suggestions="seachBusiness"
                             :trigger-on-focus="false">
                            </el-autocomplete> -->
                            <el-autocomplete v-model="comCompetitor.business"  
                             :fetch-suggestions="seachBusiness">
                            </el-autocomplete>
                        </el-form-item>
                        <el-form-item label="成立时间" label-width="90px" prop='establishTime'  >
                            <el-date-picker
                            :disabled="true"
                            v-model="comCompetitor.establishTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="估值" label-width="90px" prop='valuation'>
                            <el-input v-model="comCompetitor.valuation"  :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="logo" label-width="90px" prop='logo' :disabled="true">
                            <LogoImg  ref="logoImg" :src='comCompetitor.logo'/>
                        </el-form-item>
                        
                    </el-col>
                </el-row>
            </el-form>
            <!-- 二层弹框 -->
            <el-dialog :visible.sync="innerVisible" append-to-body>
                <CompanyInfoTable  :mainCompanySearch="mainCompanySearch"
                            ref="companyInfoTable"
                            @getName="getName">
                </CompanyInfoTable>
            </el-dialog>
            <div slot="footer" class="dialog-footer" align="center">
                <el-button type="primary" round @click="validationField()">保存</el-button>
                <el-button round @click="cancel">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Watch } from 'vue-property-decorator';
import CompititorService from '../../../../../service/subject/company/competitor-info/index';
import ProductService from '../../../../../service/subject/company/other-info/index';
import { ComCompetitorVO, PageParam, ComProductVO } from '../../../../../api/Interface';
import CompanyInfoTable from '@/components/companyTable/index.vue'; // 弹框组件
// import { CompanySearch } from '../../../../../service/common/interface';
import { ComPBJSearchDto } from '../../../../../service/subject/company/companyInterface';
import LogoImg from '@/components/logo/index.vue';
import BasicInfoService from '../../../../../service/subject/company/basic-info/index';
import OperateBtn from '../operate-btn/index.vue';

interface MainCompanySearch {
    name: string;
    searchType: string;
    attribute: number;
}
@Component({
    components: {
        CompanyInfoTable,
        LogoImg,
        Operate: OperateBtn,
    }
})
export default class BasicInfo extends Vue {
    // 初始化数据 相当于data
    // public msg: number = 123;
    public comCompetitor: ComCompetitorVO = {} as ComCompetitorVO; // 竞品的信息    添加 && 编辑 参数
    public data: object[] = [];
    public operateNum: number = 2;
    public inputValue: string = '';
    public dialogVisible: boolean = false;
    public innerVisible: boolean = false;
    public valueTime: string = '';
    public openSearchNameType: object[] = this.$store.state.user.dictionary.dicList.openSearchNameType;
    public mainCompanySearch: MainCompanySearch = {} as MainCompanySearch;  // // 竞品公司 模糊搜索 的参数 往组件传递的参数
    public companyId: string = ''; // 工商id （大id）
    public competitorList: ComCompetitorVO[] = [] as ComCompetitorVO[]; // 列表数据
    public companySearchInfo: ComPBJSearchDto = {   operate: 1} as ComPBJSearchDto; // 竞品列表查询的参数
    public pageParam: PageParam =  { pageIndex: 1, pageSize: 10 }  as PageParam;
    public totalCount: number = 0; // 总数
    public productList: ComProductVO[] = [] as ComProductVO[]; // 产品列表
    public searchType: string = ''; // 模糊查询类型
    public state: string = '添加'; // 添加 or 编辑
    public rules = {
        competitorCompanyName: [ { required: true, message: '请输入公司名称', trigger: 'blur' } ],
        competitorProductId: [ { required: true, message: '请选择产品', trigger: 'change' } ],
    };
    // refs
    public $refs: {
        companyInfoTable: HTMLFormElement;
        competiteForm: HTMLFormElement;
        logoImg: any,
     };

    // watch
    @Watch('msg')
    public onChildChanged(val: string, oldVal: string) {
        return val + '***';
    }
      // 模糊搜索行业
    public async seachIndustry(val: string, cb: (obj?: object) => void) {
        if (!val) { val = ''; }
        const res = await ProductService.searchBusiness(val);
        const data: object[] = [];
        if (res && res.length !== 0) {
            res.map((item: string) => {
                data.push({value: item });
            });
        }
        cb(data);
    }
     // 模糊搜索业务
    public async seachBusiness(val: string, cb: (obj?: object) => void) {
        if (!val) { val = ''; }
        const res = await ProductService.searchBusiness(val);
        const data: object[] = [];
        if (res && res.length !== 0) {
            res.map((item: string) => {
                data.push({value: item });
            });
        }
        cb(data);
    }
   
    public addDialog() {
        this.state = '添加';
        this.comCompetitor = {logo: ''} as ComCompetitorVO;
        this.productList = [] as ComProductVO[];
        this.dialogVisible = true;
    }
    public cancel() {
       this.dialogVisible = false;
       this.resetForm('competiteForm');
       this.getCompetitorList();
    }
    public resetForm(formName: string) {
      this.$refs[formName].resetFields();
    }
    // 改变产品名称
    public changeProduct(val: number) {
        if ( this.productList &&  this.productList.length !== 0) {
           this.productList.map((item: ComProductVO) => {
                if (val === item.id) {
                    this.comCompetitor.productName = item.product;
                    this.comCompetitor.logo = item.logoUrl;
                    // this.$set(this.comCompetitor, 'logo', item.logoUrl);
                }
           });
        }
    }
    // public onSuccess(imgId: string) {
    //     this.comCompetitor.logo = imgId;
    //     this.save();
    // }
    // 声明周期钩子
    public mounted() {
        this.companyId =  this.$route.params.itemId;
        this.refreshList();
        this.getCompetitorList();
    }
    // 获取竞品的列表
    public async getCompetitorList() {
            this.companySearchInfo = {
                 operate: this.operateNum,
                 companyId: Number(this.companyId),
                'pageParam.pageIndex': this.pageParam.pageIndex,
                'pageParam.pageSize': this.pageParam.pageSize,
            };
            const res = await CompititorService.getComCompetitorPage(this.companySearchInfo);
            this.totalCount = res.totalCount;
            this.competitorList = res.resultData;
    }
     // 查询企业信息--获取企业名字
    public async getEnterprise() {
          if (!this.comCompetitor.competitorCompanyName) {
            this.$message.warning('请填写搜索名称！');
        } else if (!this.searchType) {
            this.$message.warning('请选择搜索类型！');
        } else {
            this.innerVisible = true;
           
            this.$set(this.mainCompanySearch, 'name', this.comCompetitor.competitorCompanyName);
            this.$set(this.mainCompanySearch, 'searchType', this.searchType);
            this.$set(this.mainCompanySearch, 'attribute', 1);
            this.$nextTick(() => {
                this.$refs.companyInfoTable.getCompanyOpenSearchData();
            });   
        }
    }
    // 组件 获取竞品公司的id+name
    public getName(company: {id: number, name: string}) {
        this.comCompetitor.competitorCompanyName = company.name;
        this.comCompetitor.competitorCompanyId = company.id;
          // this.comCompetitor.competitorCompanyId = 1526437473735; // =====================================>临时数据
        this.innerVisible = false;
        // 根据 id 获取 信息
        this.getCompanyInfo();
    }
    // 模糊搜索后，选择公司后，获取公司信息
    public async getCompanyInfo() {
        const res = await CompititorService.getComInfoById(this.comCompetitor.competitorCompanyId);
        // 根据模糊搜索的数据 来 进行 页面赋值
         this.productList = res.comProductVOList; // 相应公司的产品列表
         // 所选竞品的公司的信息: 不随竞品的选择改变 
         this.$set(this.comCompetitor, 'valuation', res.valuation);
         this.$set(this.comCompetitor, 'establishTime', res.establishTime + '');
         this.$set(this.comCompetitor, 'competitorRound', res.investRound);
         this.$set(this.comCompetitor, 'productName', res.investRound);
         this.$set(this.comCompetitor, 'competitorArea', res.area);

         if (this.state === '编辑') {
             // 产品名称对应的 logo
              this.changeProduct(this.comCompetitor.competitorProductId);
         }
    }
    //验证字段
    public validationField() {
        this.$refs.competiteForm.validate((valid: boolean) => {
            if (valid) {
               this.save();
            } else {
                return;
            }
        });
    }
    // 获取运营状态值
    public getOperateNum(Num: number) {
        this.operateNum = Num;
        this.getCompetitorList();
    }
    // 添加竞品 && 编辑竞品
    public async save() {
        if (this.state === '添加') { // 添加竞品
        //    console.log('添加')
            this.comCompetitor.companyId = Number(this.companyId);
            const res = await CompititorService.saveComCompetitor(this.comCompetitor);
            if (res.resCode === '0') {
                this.$message.success('添加成功！');
                this.dialogVisible = false;
                this.getCompetitorList();
                this.resetForm('competiteForm');
            }
        } else { // 编辑竞品
        //   console.log('编辑')
            const res = await CompititorService.updateComCompetitor(this.comCompetitor);
            if (res.resCode === '0') {
                this.$message.success('编辑成功！');
                this.dialogVisible = false;
                this.getCompetitorList();
                this.resetForm('competiteForm');
            }
        }
    }
    // 编辑
    public async editInfo(info: ComCompetitorVO) {
       this.state = '编辑';
       const comCompetitorInfo = JSON.parse(JSON.stringify(info)); // 复制列表数据
       this.comCompetitor = comCompetitorInfo; // 编辑显示赋值
       this.comCompetitor.establishTime = comCompetitorInfo.establishTime + ''; // 时间处理
       
       // 产品下拉 及相对应的logo等信息
       this.getCompanyInfo();
       
       this.dialogVisible = true;
    }
    // 删除
    public async deleteInfo(id: number) {
        this.$confirm('是否删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
            const res = await CompititorService.deleteComCompetitorById(id);
            if (res.resCode === '0') {
            this.$message({
                    message: '删除成功！!',
                    type: 'success',
                    center: true
                });
                this.getCompetitorList();
            }
        }).catch(() => {
            return false;         
        });
    }
    // 获取运营标记并刷新列表
    public async refreshList() {
        const res = await BasicInfoService.getCompanyById(Number(this.$route.params.itemId));
        if (res.resCode === '0') {
            this.operateNum = res.data.competitorOperate;
            this.getCompetitorList();
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.diable{
    cursor: not-allowed
}
.ca-title {
    height: 50px;
    overflow: hidden;
    line-height: 50px;
}
.ca-title h3{
    font-weight: normal;
    font-size: 18px;
    color: #333333;
    float: left;
}
.line-h {
    line-height: 36px;
}
.addBtn {
    font-size: 22px;
    margin-top: 12px;
    margin-left: 10px;
}
.el-checkbox+.el-checkbox {
    margin-right: 10px;
}
.el-checkbox {
    color: #606266;
    font-size: 14px;
    cursor: pointer;
    user-select: none;
    margin-left: 10px;
}
</style>